package cn.china.xfood.controller.foods;


import cn.china.xfood.service.ProductService;
import cn.china.xfood.util.RedisConfig;
import com.sun.org.apache.xpath.internal.operations.Bool;
import entity.Product;
import entity.Student;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
public class Foods {

    @Autowired
    ProductService productService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/getByType")
    public List<Product> getByType(@RequestParam String type, @RequestParam String currentPage, HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        int page = Integer.parseInt(currentPage);
        int pageCount = 8;
        int currentpage = (page-1)*pageCount;
        return productService.getByType(type,currentpage,pageCount);
    }

    @RequestMapping("/getCountByType")
    public double getProductService(@RequestParam String type, HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        int countByType = productService.getCountByType(type);
        int pageCount = 4;
        int ceil = (int) Math.ceil(countByType / pageCount);
        return ceil;

    }

    @RequestMapping("/addCar")
    public String addCar(HttpServletRequest request, HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        String id = request.getParameter("id");
        String url = request.getParameter("url");
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String username = request.getParameter("username");
        String remarks = request.getParameter("remarks");
        System.out.println("remarks:"+remarks);
//        System.out.println("id:"+id);
//        System.out.println("url:"+url);
//        System.out.println("name:"+name);
//        System.out.println("price:"+price);
//        System.out.println("账户："+username);

        Product product = new Product();
        product.setId(Integer.parseInt(id));
        product.setProductUrl(url);
        product.setProductName(name);
        product.setProductPrice(Double.parseDouble(price));
        product.setProductAmount(1);

//        Product product1 = productService.selectByPrimaryKey(Integer.parseInt(id));

        List<Object> range = redisTemplate.opsForList().range(username, 0, redisTemplate.opsForList().size(username) - 1);
            if (!(range.isEmpty())){
                boolean flags = false;
                for (int i = 0; i < range.size() ; i++) {
                    Product p = (Product) range.get(i);
//                     如果后来添加的菜名，list集合已经添加过了 ,给此菜数量+1
                    if ( flags = name.equals(p.getProductName())) {
                        p.setProductAmount(p.getProductAmount() + 1);
                        break;
                    }
                }
                if(flags != true){
                    range.add(product);
                }

            } else{
                range.add(product);
            }
        System.out.println(range);

            redisTemplate.opsForList().getOperations().delete(username);
            redisTemplate.opsForList().leftPushAll(username, range);


        return "添加成功";

    }


    @RequestMapping("/addProduct")
    public Boolean addProduct(@RequestParam String data,HttpServletResponse res){
        res.setHeader("Access-Control-Allow-Origin","*");
//            request.getParameterNames(data);

//
//        StringBuilder sb = new StringBuilder();
//        try(BufferedReader reader = request.getReader()) {
//            char[]buff = new char[1024];
//            int len;
//            while((len = reader.read(buff)) != -1) {
//                sb.append(buff,0, len);
//            }
//        }catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("sb:"+sb);


        System.out.println(data);

        return true;
    }


    @RequestMapping(value ="/upFile",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upFile(@RequestParam("p_type") String p_type, @RequestParam("p_name") String p_name, @RequestParam("p_num") Integer p_num, @RequestParam("price") Double price, @RequestParam("intro") String intro, @RequestParam("picID") MultipartFile multipartFile, HttpServletResponse res) throws  IOException {
        res.setHeader("Access-Control-Allow-Origin","*");

        String realPath = ResourceUtils.getURL("classpath:").getPath();//获取classes的路径
        String originalFilename=multipartFile.getOriginalFilename();//获取图片原始的名称
        System.out.println("=======我上传的图片名称是:"+originalFilename);

        long l=System.currentTimeMillis();//获取当前毫秒数
        String newName=l+originalFilename;
        System.out.println("=======毫秒数+原始名称:"+newName); //封装图片的名字信息（毫秒数+名称即图片的编号）


        InputStream inputStream=multipartFile.getInputStream();//输入流,用来读取图片

        System.out.println("路径"+realPath);

//在项目根目录下创建image文件夹.用来保存上传的图片           创建文件夹保存
        File file=new File(realPath+"/static/images/");
        if(!(file.exists())){
            file.mkdirs();//如果这个文件不存在,创建文件夹
        }
/*

        File filefinal = new File();
        File file1 = new File(realPath+"/static/images/hot"+newName);

        switch (p_type){
            case "main":
            case "hot":
            case "cold":
            case "soup":
            case "drink":
        }
*/


        if(!multipartFile.isEmpty()){
            FileOutputStream fos=new FileOutputStream(realPath+"/static/images/hot"+newName);

            int length=0;
            while((length=inputStream.read())!=-1){
                fos.write(length);
            }
            fos.flush();
            fos.close();
            inputStream.close();

        }

        String url="http://localhost:8090/images/"+newName;
        Product product=new Product();
        product.setProductName(p_name);
        product.setProductAmount(p_num);
        product.setProductPrice(price);
        product.setProductType(p_type);
        product.setProductUrl(url);
        productService.insertSelective(product);

        return "---";
    }


    @RequestMapping("/offProduct")
    public String offProduct(@RequestParam String id ,HttpServletResponse res ){
        res.setHeader("Access-Control-Allow-Origin","*");

        int p_id = Integer.parseInt(id);
        int i = productService.deleteByPrimaryKey(p_id);
        if(i>0){
            return "下架成功！";
        }else{
            return "下架失败!";
        }

    }

}